package DMSXL._2024.BackTracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class combinationSum2 {
    public static void main(String[] args) {
        int[] can = {10,1,2,7,6,1,5};
        int target = 8;
        System.out.println(new combinationSum2().combinationSum2(can,target));
    }
    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        boolean[] used = new boolean[candidates.length];
        for (int i = 0; i < used.length; i++) {
            used[i] = false;
        }
        Arrays.sort(candidates);
        backTracking(candidates,target,0,0,used);
        return result;
    }
    public void backTracking(int[] candidates, int target, int num, int startIndex, boolean[] used){
        if(target == num){
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i < candidates.length && num + candidates[i] <= target; i++) {
            if(i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1]){
                continue;
            }
            path.add(candidates[i]);
            num += candidates[i];
            used[i] = true;
            backTracking(candidates,target,num,i + 1,used);
            used[i] = false;
            num -= candidates[i];
            path.removeLast();
        }
    }

}
